package service

import (
	"gin/model"
	"gin/validate"
	uuid "github.com/satori/go.uuid"
	"github.com/spf13/viper"
	"os"
	"strings"
)

// 验证文件md5是否存在
func CheckFileMd5(MD5 string) (check bool, fileData model.Package) {
	var filesModel model.Package
	var err error

	fileData, err = filesModel.GetFileDataByMD5(MD5)
	if err != nil {
		check = false
	} else {
		check = true
	}

	return
}

// 保存文件数据
func CreateFile(Data validate.AddFile) (err error) {
	var filesModel model.Package
	filesModel.Name = Data.Name
	filesModel.Md5 = Data.Md5
	filesModel.Type = Data.Type
	filesModel.Version = Data.Version
	filesModel.Param = Data.Param
	filesModel.Path = Data.Path

	// 填充UUID
	filesModel.Uuid = uuid.NewV4().String()

	_, err = filesModel.Insert()

	return
}

// 通过 Name 查找文件
func SelectFileByName(Name string) (fileData []model.Package, err error) {
	var fileModel model.Package
	fileData, err = fileModel.SelectFileByName(strings.Split(Name, ","))
	return
}

// 删除文件通过 Name
func RemoveFileByName(Name string) (err error) {
	var fileModel model.Package

	// 1.先查找当前存在的文件
	fileData, err := fileModel.SelectFileByName(strings.Split(Name, ","))

	if err != nil {
		return
	}

	// 删除存在数据的文件夹
	basePath := viper.GetString("server.staticPath")
	for _, fileItem := range fileData {
		err = os.RemoveAll(basePath + fileItem.Name)
		if err != nil {
			break
		}
	}

	if err != nil {
		return
	}

	// 清除数据库数据
	err = fileModel.RemoveFileByName(strings.Split(Name, ","))
	return
}
